package com.roundarch.www.util.propertyeditor;

import java.beans.PropertyEditorSupport;

import com.roundarch.www.DataEntity;
import com.roundarch.www.service.EntityService;




public class EntityPropertyEditor<T extends DataEntity> extends PropertyEditorSupport
{
    private EntityService entityService;
    private Class<T> entityClass;

    public EntityPropertyEditor(EntityService entityService, Class<T> entityClass)
    {
        setEntityService(entityService);
        setEntityClass(entityClass);
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException
    {
        T entity = getEntityService().find(Long.parseLong(text),getEntityClass());
        setValue(entity);
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getAsText()
    {
        T entity = (T) getValue();
        if (entity == null)
            return "";

        return Long.toString(entity.getId());
    }

    public EntityService getEntityService()
    {
        return entityService;
    }

    public void setEntityService(EntityService entityService)
    {
        this.entityService = entityService;
    }

    public Class<T> getEntityClass()
    {
        return entityClass;
    }

    public void setEntityClass(Class<T> entityClass)
    {
        this.entityClass = entityClass;
    }
}
